package com.qunar.wan.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

/**
 * User: huiming.suo Date: 13-12-2 Time: 下午3:23
 */
public class ImageHelper {
    static Logger logger = LoggerFactory.getLogger(ImageHelper.class);
    /**
     * 截取图片：
     * <p/>
     * 把原图片截取成选中尺寸大小和坐标的图片
     * 
     * @param left 选择图片的左坐标
     * @param top 选择图片的顶部坐标
     * @param width 选择图片的宽度
     * @param height 选择图片的高度
     * @param fis 目标图片路径
     * @param fileSuffix 目标图片的格式
     * @param newPath 截取后图片存储的路径包括文件名及格式
     */
    public static void cutImage(InputStream fis, String newPath, String fileSuffix, int left, int top, int width,
            int height) throws IOException {

        Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(fileSuffix);
        ImageReader imageReader = iterator.next();
        ImageInputStream iis = null;
        try {
            iis = ImageIO.createImageInputStream(fis);
            imageReader.setInput(iis, true);
            ImageReadParam param = imageReader.getDefaultReadParam();
            param.setSourceRegion(new Rectangle(left, top, width, height));
            BufferedImage bi = imageReader.read(0, param);
            boolean result = ImageIO.write(bi, fileSuffix, new File(newPath));
            logger.info("截取图片{}{}",newPath,result?"成功":"失败");
        } finally {
            if (iis != null) {
                iis.close();
            }
        }

    }
}
